import { Component } from 'react'
import Taro from '@tarojs/taro'
import { View, Text, Image } from '@tarojs/components'
import { AtTag, AtLoadMore } from 'taro-ui'
import classnames from 'classnames'

import * as api from 'src/api'
import Empty from 'src/components/Empty'
import { orderState } from 'src/constants'
import withPage from 'src/utils/withPage'

import './index.scss'

type IProps = {}

type IState = {
  currentState: number
  orderData: { [key: string]: any }
  orderList: any[]
  listStatus?: 'more' | 'loading' | 'noMore'
  page: number
  limit: number
}

interface Index {
  props: IProps
  state: IState
}

@withPage()
class Index extends Component {
  state: IState = {
    currentState: 9,
    orderData: {},
    orderList: [],
    listStatus: 'more',
    page: 1,
    limit: 10,
  }

  async componentDidShow() {
    await this.getData()
  }

  async onPullDownRefresh() {
    await this.getData()
    Taro.stopPullDownRefresh()
  }

  getData = async () => {
    this.setState(
      {
        orderList: [],
        page: 1,
      },
      async () => {
        await Promise.allSettled([this.getOrderData(), this.getOrderList()])
      }
    )
  }

  getOrderData = async () => {
    const orderData: any = await api.getOrderData()
    this.setState({ orderData })
  }

  getOrderList = async () => {
    type Data = {
      type?: number
      shippingType?: number
      page: number
      limit: number
    }
    const { currentState, orderList, page, limit } = this.state
    let data: Data = {
      type: currentState,
      page,
      limit,
    }
    if (this.state.currentState === -1) {
      data.type = 1
      data.shippingType = 2
    } else if (this.state.currentState === 1) {
      data.shippingType = 1
    } else if (this.state.currentState === 9) {
      data = {
        page: page,
        limit: limit,
      }
    }
    this.setState({ listStatus: 'loading' })
    const res = await api.getOrderList(data)
    const list = res || []
    this.setState({
      orderList: orderList.concat(list),
      listStatus: list.length < limit ? 'noMore' : 'more',
    })
  }

  handleClickOrderTab = (status: number) => {
    if (status == this.state.currentState) return
    this.setState(
      {
        currentState: status,
        orderList: [],
        listStatus: 'more',
        page: 1,
      },
      () => {
        this.getOrderList()
      }
    )
  }

  getMoreList = () => {
    this.setState({ page: this.state.page + 1 }, () => {
      this.getOrderList()
    })
  }

  goOrderDetails = (order_id: string) => {
    Taro.navigateTo({
      url: '/pages/order_detail/index?order_id=' + order_id,
    })
  }

  render() {
    const { currentState, orderData, orderList, listStatus } = this.state
    return (
      <View>
        <View className="order-bg">
          <View className="picTxt at-row at-row__justify--between at-row__align--center">
            <View className="text">
              <View className="name">订单信息</View>
              <View>
                消费订单:{orderData.orderCount || 0} 总消费:￥
                {Number(orderData.sumPrice).toFixed(2) || 0}
              </View>
            </View>
            <Image
              className="pictrue"
              src={require('src/static/images/orderTime.png')}
            ></Image>
          </View>
        </View>
        <View className="order-nav at-row at-row__justify--around">
          {orderState.map((item, index) => (
            <View
              className={classnames('item', {
                on: item.status === currentState,
              })}
              key={index}
              onClick={() => this.handleClickOrderTab(item.status)}
            >
              <View>{item.title}</View>
              <View className="num">{orderData[item.num] || 0}</View>
            </View>
          ))}
        </View>
        {orderList.length > 0 || listStatus === 'loading' ? (
          <>
            <View className="order-list">
              {orderList.map((item) => (
                <View
                  className="item"
                  key={item.storeOrder.orderId}
                  onClick={() => this.goOrderDetails(item.storeOrder.orderId)}
                >
                  <View className="header at-row at-row__justify--between at-row__align--center">
                    <View className="time">{item.storeOrder.createTime}</View>
                    {item.storeOrder.shippingType === 2 && (
                      <AtTag size="small" type="primary" active>
                        自提
                      </AtTag>
                    )}
                    <View className="status at-col">
                      {
                        orderState.find(({ status }) => {
                          let type = item.status?.type
                          const shippingType = item.storeOrder?.shippingType
                          if (type === 1 && shippingType === 2) {
                            type = -1
                          }
                          return type === status
                        })?.title
                      }
                    </View>
                  </View>
                  {item.cartInfo.map((cartInfo, index) => (
                    <View
                      className="body at-row at-row__justify--between at-row__align--start"
                      key={index}
                    >
                      <Image
                        className="pictrue"
                        src={cartInfo.info.productInfo.image}
                      ></Image>
                      <View className="name line2 at-col">
                        {cartInfo.info.productInfo.storeName}
                      </View>
                      <View className="money">
                        <View>
                          ￥
                          {cartInfo.info.productInfo.attrInfo
                            ? cartInfo.info.productInfo.attrInfo.price
                            : cartInfo.info.productInfo.price}
                        </View>
                        <View>x{cartInfo.info.cartNum}</View>
                      </View>
                    </View>
                  ))}
                  <View className="footer at-row at-row__justify--between at-row__align--center">
                    {currentState === 0 && (
                      <View className="store">付款门店:{item.shop.name}</View>
                    )}
                    <View className="total-price at-col">
                      实付合计
                      <Text className="price-color">
                        ￥{item.storeOrder.payPrice}
                      </Text>
                    </View>
                  </View>
                </View>
              ))}
            </View>
            <AtLoadMore
              onClick={this.getMoreList}
              status={listStatus}
              noMoreTextStyle={{ fontSize: 12 }}
            />
          </>
        ) : (
          <Empty />
        )}
      </View>
    )
  }
}

export default Index
